<template>
	<view class="seller_apply">
		<view class="seller_card">
			<view class="seller_form_item" style="padding-bottom: 24rpx;">
				<view class="item_header row">
					<text>Product Name</text>
					<image src="@/static/required.png" mode=""></image>
				</view>
				<input v-model="formData.name" type="text" placeholder="Please enter the product name" />
			</view>
			<view class="seller_form_item">
				<view class="item_header row">
					<text>Product picture</text>
					<image src="@/static/required.png" mode=""></image>
				</view>
				<!-- <text class="item_gray">Click to upload shop details</text>ss -->
				<u-upload :fileList="fileList" uploadIconColor="#ffffff" width="141rpx" height="133rpx"
					@afterRead="afterRead" @delete="deletePic" multiple :maxCount="9"></u-upload>
			</view>
			<!-- 	<view class="seller_form_item">
				<view class="item_header row">
					<text>detail images</text>
					<image src="@/static/required.png" mode=""></image>
				</view>
				<u-upload :fileList="detailList" width="141rpx" height="133rpx" uploadIcon="plus"
					@afterRead="afterRead1" @delete="deletePic1" multiple :maxCount="9"></u-upload>
			</view> -->
			<view class="seller_form_item">
				<view class="item_header row" style="padding-bottom: 0;">
					<text>Products descriptions </text>
					<image src="@/static/required.png" mode=""></image>
				</view>
				<u--textarea v-model="formData.introduce" border="none" style="padding:18rpx 0;"
					placeholder="Enter up to 60 characters for your dish’s quick note." count
					:maxlength="60"></u--textarea>
			</view>
		</view>
		<view class="seller_card">
			<view class="seller_form_item row">
				<view class="item_header row" style="margin-right: 16rpx;margin-top: 8rpx;">
					<text>Price</text>
					<image src="@/static/required.png" mode=""></image>
				</view>
				<input v-model="formData.origin_price" type="number" @input="handlePrice" placeholder="0.00" />
			</view>
			<view class="seller_form_item row">
				<view class="item_header row" style="margin-right: 16rpx;margin-top: 8rpx;">
					<text>Discount</text>
					<image src="@/static/required.png" mode=""></image>
				</view>
				<input class="discount" v-model="formData.discount" @input="handleDiscount"  type="number" :max="100" placeholder="" />
				<span style="color:#939393;">%</span>
				<text>discount price:{{discountPrice}}</text>
			</view>
			<view class="seller_form_item row">
				<view class="item_header row" style="margin-right: 16rpx;margin-top: 8rpx;">
					<text>Discount</text>
					<!-- <image src="@/static/required.png" mode=""></image> -->
				</view>
				<text style="color:#939393;">amount reach</text>
				<input class="minus" v-model="formData.reach" type="number" placeholder="" />
				<text style="color:#939393;">minus</text>
				<input class="minus" v-model="formData.minus" type="number" placeholder="" />
			</view>
		</view>
		<view class="footer row">
			<button class="btn-01" @click.stop="handleSubmit('1')">Save and upload</button>
			<button class="btn-02" @click.stop="handleSubmit('0')">Save and off shelf</button>
		</view>
	</view>
</template>

<script>
	import {
		policy,
		addGoods,
		editItem,
		itemDetailForShoper,
		getDiscountPrice
	} from '@/lib/service';
	import {
		showFailure,
		showMessage,
		showSuccess
	} from '@/lib/helper';
	export default {
		data() {
			return {
				fileList: [],
				detailList: [],
				itemid: "",
				discountPrice: "0.00",
				formData: {
					name: "",
					imgurls: "",
					introduce: "",
					origin_price: "",
					discount: "",
					state: "0",
				}
			};
		},
		onLoad(options) {
			this.itemid = options.itemid;
			if (this.itemid) {
				this.handleInfo()
			}
		},

		methods: {
			handleInfo() {
				let _this = this;
				itemDetailForShoper({
					itemid: this.itemid
				}).then((res) => {
					if (res.statusCode == 0) {
						this.formData = res.data;
						if (this.formData.imgurls) {
							this.fileList = this.formData.imgurls.split(',').map(item => ({
								url: item
							}));
						}
						_this.onDiscountPrice()
					}
				}).catch((res) => {

				});
			},
			onDiscountPrice() {
				let _this = this;
				if(_this.formData.origin_price&&_this.formData.discount){
					getDiscountPrice({
						origin_price: _this.formData.origin_price,
						discount: _this.formData.discount
					}).then((res) => {
						if (res.statusCode == 0) {
							_this.discountPrice = res.data.discount_price || '0.00';
						}
					}).catch((res) => {
					_this.discountPrice  = '0.00'
					});
				}
				
			},
			handlePrice(e){
			   console.log(e)	
			   this.formData.origin_price = e.detail.value;
			   this.onDiscountPrice()
			},
			handleDiscount(e){
				this.formData.discount = e.detail.value;
				this.onDiscountPrice()
			},
			deletePic(event) {
				this.fileList.splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this.fileList.length;
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i]);
					let item = this.fileList[fileListLen];
					this.fileList.splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise(file) {
				let name = file.name ? file.name : file.url.split('/').pop();
				return new Promise((resolve, reject) => {
					policy('house', name).then((res) => {
						let a = uni.uploadFile({
							url: res.data.signedUrl, // 仅为示例，非真实的接口地址
							filePath: file.url,
							name: 'file',
							success: (res) => {
								try {
									var data = JSON.parse(res.data);
									resolve(data.data);
								} catch (e) {
									console.log(e);
								}
							}
						});
					});
				});
			},
			validateFormWithDetails(data) {
				const fieldNames = {
					name: "Product Name",
					imgurls: "Product picture",
					// detailurls: "detail images",
					introduce: "Description",
					price: "Price",
					discount: "Discount",
					// reach: "amount reach",
					// minus: "minus",
				};
				for (let key in data) {
					if (data.hasOwnProperty(key)) {
						if ((key == 'detailurls' || key == 'reach' || key == 'minus') && (data[key] === null || data[
								key] === undefined || data[key] === '')) {
							return {
								isValid: true,
								field: key,
								fieldName: fieldNames[key] || key,
								message: `${fieldNames[key] || key} Cannot be empty`
							};
						} else if ((key != 'detailurls' || key != 'reach' || key != 'minus') && (data[key] === null ||
								data[key] === undefined || data[key] === '')) {
							return {
								isValid: false,
								field: key,
								fieldName: fieldNames[key] || key,
								message: `${fieldNames[key] || key} Cannot be empty`
							};
						}
					}
				}
				return {
					isValid: true
				};
			},
			handleSubmit(state) {
				this.formData.state = state;
				if (this.fileList.length > 0) {
					this.formData.imgurls = this.fileList.map(item => item.url).join(',')
				}
				// if (this.detailList.length > 0) {
				// 	this.formData.detailurls = this.detailList.map(item => item.url).join(',')
				// }
				let validateResult = this.validateFormWithDetails(this.formData);
				if (!validateResult.isValid) {
					uni.showToast({
						title: validateResult.message,
						icon: 'none'
					});
					return;
				}
				uni.showLoading();
				if (this.itemid) {
					this.formData.itemid = this.itemid;
					editItem(this.formData).then((res) => {
						showSuccess();
						uni.hideLoading();
						uni.redirectTo({
							url: './menu'
						});
					}).catch((err) => {
						uni.hideLoading();
						showFailure();
					});
				} else {
					addGoods(this.formData).then((res) => {
						showSuccess();
						uni.hideLoading();
						uni.redirectTo({
							url: './menu'
						});
					}).catch((err) => {
						uni.hideLoading();
						showFailure();
					});
				}
			}
		}
	}
</script>
<style lang="scss" scoped>
	.seller_apply {
		padding: 36rpx 28rpx;
		padding-bottom: 140rpx;

		.seller_card {
			border-radius: 22.9rpx;
			padding: 16rpx 20rpx;
			box-shadow: 0rpx 0rpx 19.08rpx rgba(239, 239, 239, 0.79);
			margin-bottom: 24rpx;

			.seller_form_item {
				.discount {
					width: 188rpx;
					height: 38rpx;
					background: rgba(51, 51, 51, 0.04);
					border-radius: 7.63rpx;
					padding: 0 12rpx;
					margin-right: 8rpx;
				}

				>text {
					font-size: 26rpx;
				}

				.minus {
					width: 91.6rpx;
					height: 38.17rpx;
					background: rgba(51, 51, 51, 0.04);
					border-radius: 7.63rpx;
					margin: 0 8rpx;
					padding: 0 12rpx;
				}

				.item_header {
					padding-bottom: 16rpx;

					text {
						font-family: PingFang SC;
						font-weight: 500;
						color: #272727;
						font-size: 24rpx;
					}

					image {
						width: 14rpx;
						height: 12rpx;
						margin-right: 8rpx;
					}
				}

				.item_gray {
					font-family: PingFang SC;
					color: #939393;
					font-size: 22rpx;
					display: block;
					padding-bottom: 16rpx;
				}
			}
		}
	}

	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		padding: 30rpx 0;
		background: #ffffff;

		button {
			width: 300rpx;
			border-radius: 50rpx;
			height: 92rpx;
			background: #fc721a;
			line-height: 92rpx;
			font-family: Montserrat;
			font-weight: 500;
			color: #ffffff;
			font-size: 26rpx;
			text-align: center;
			padding: 0;
		}

		.btn-01 {
			background: #facdb0;
			color: #1c1c1c;
		}
	}
</style>